import crcmod

# 创建一个16位CRC模块，初始CRC值为0x0000，多项式为0xA001
# crc16 = crcmod.predefined.Crc('crc-16-modbus')
# 创建一个CRC对象，‌使用预定义的CRC-16算法
crc16 = crcmod.predefined.Crc('crc-16')


# crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)


class CRCUtil:
    @staticmethod
    def crc16(data):
        crc = 0xFFFF
        for i in data:
            crc = crc ^ (i << 8)
            for _ in range(8):
                if crc & 0x8000:
                    crc = (crc << 1) ^ 0x1021
                else:
                    crc = crc << 1
        return crc

    @staticmethod
    def crc_16(data):
        crc16.update(data.encode("utf-8"))
        crc_bytes = crc16.digest()
        # print(f"crc_bytes: {crc_bytes}")
        hex_str = crc_bytes.hex()
        return hex_str


if __name__ == '__main__':
    # res = CRCUtil.crc16(b"hello world")
    # print(res)
    CRCUtil.crc_16("010302020002")

    pass
